<template>
    <el-dialog class="create-entity-dialog" title="生成实体" width="85%"
               :visible.sync="visible" :before-close="handleClose">

        <div>
            <template v-for="table in tables">
                <h4 v-text="table.name"></h4>
                <p>entity</p>
                <ac-high-light :value="table.entity"></ac-high-light>
                <p>bean</p>
                <ac-high-light :value="table.bean"></ac-high-light>
                <p>convert</p>
                <ac-high-light :value="table.convert"></ac-high-light>
                <br><br>
                <hr>
            </template>
        </div>

        <div slot="footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="success" @click="saveClick">保存文件</el-button>
        </div>
    </el-dialog>
</template>

<script type="text/ecmascript-6">
    import entity from '../model/entity';
    import bean from '../model/bean';
    import convert from '../model/convert';
    import path from 'path';
    import fs from 'fs';
    import AcHighLight from "../common/HighLightTextArea";

    /**
     * @author 白雨浓
     * @date 2018/1/14 14:08
     *
     * 生成Entity和Bean窗口
     **/
    export default {
        components: {AcHighLight},
        name: 'AcCreateEntityDialog',
        props: ['dialogVisible', 'tableNames', 'config',],
        data() {
            return {
                visible: this.dialogVisible,
                msg: '',
                tables: []
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.tables = [];
                this.tableNames.forEach(name => {
                    this.selectTable(name);

                    /*保存最近生成的实体类，用于MVC快速生成*/
                    this.$storage.session.setItem('recent-entity', {table: name});
                });
            })
        },
        methods: {
            async selectTable(name) {
                const sql = `SELECT * FROM information_schema.COLUMNS
                WHERE table_schema = '${this.config.dbName}'
                AND table_name = '${name}';`;

                const fields = await this.$db.query(sql);
                fields.forEach(field => field.COLUMN_NAME = field.COLUMN_NAME.toLowerCase());
                this.tables.push({
                    name: name,
                    entity: entity.entity(this, name, fields),
                    bean: bean.bean(this, name, fields),
                    convert: convert.convert(this, name),
                });
            },
            saveClick() {
                let projectPath = this.config.projectPath;

                if (projectPath[projectPath.length - 1] !== '/')
                    projectPath += '/';
                projectPath += 'src/main/java/';
                projectPath += this.config.packageName.replace(/\./g, '/');

                if (!fs.existsSync(path.join(projectPath))) {
                    this.$$msg.error('工程目录不存在，请检查基础设置-ProjectPath');
                    return;
                }

                for (const table of this.tables) {
                    let clsName = this.$str.toCamel(table.name);
                    clsName = clsName.substring(0, 1).toUpperCase() + clsName.substring(1);

                    this.writeFile(projectPath, `entity`, `${clsName}Entity`, table.entity);
                    this.writeFile(projectPath, `bean`, `${clsName}Bean`, table.bean);
                    this.writeFile(projectPath, `convert`, `${clsName}Convert`, table.convert);
                }
                this.handleClose();
            },
            writeFile(projectPath, packageName, filename, text) {
                const filePath = path.join(projectPath + `/${packageName}/`, filename + '.java');

                if (fs.existsSync(filePath)) {
                    this.$notify({
                        title: '提示',
                        message: `${filename}.java 文件已经存在！`,
                        type: 'error',
                        duration: 0
                    });
                    return false;
                }
                fs.writeFileSync(filePath, text);
                return true;
            },
            /** 关闭处理 */
            handleClose() {
                this.visible = false;
                setTimeout(() => this.$emit('update:dialogVisible', false), 300);
            }
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .create-entity-dialog {
    }
</style>